#include <config.h>
#include <board.h>
#include <init.h>
#include <os.h>
#include <bitmap.h>
#include <bitops.h>
#include <settings.h>
#include "ES8P508x.h"
#include "lib_config.h"
#include "device.h"
#include "printk.h"
#include "es8p508_led.h"

static struct device led_dev;

#define LED_EXPIRES	10 //100ms

static enum LED_state led_s =STATE_LED_OFF;
static int led_flash_cnt = 0;
void led_blink(void)
{
    static uint32_t led_count = 0 ;
    if(++led_count >5 )
    {
        led_count = 0;
        LED_TOGGLE;
    }

}

static void led_tmr_cb(struct soft_timer *st)
{
    uint8_t cmd = (uint8_t)led_s;
    st->expires = jiffies +  LED_EXPIRES;
    soft_timer_add(st);
	
	if(led_flash_cnt > 0)
	{
		led_flash_cnt --;
		LED_TOGGLE;
		return ;
	}
    switch (cmd)
    {
    case STATE_LED_BLINK:
        LED_TOGGLE;
        break;
    case STATE_LED_ON:
        LED_ON;
        break;
    case STATE_LED_OFF:
        LED_OFF;
        break;
    case STATE_LED_BLINK_500:
        led_blink();
        break;
    default:
        LED_OFF;
        break;
    }
}

static err_t led_ctrl(device_t *dev, uint8_t cmd, void *args)
{
    if((enum LED_state)cmd == STATE_LED_FLASH_3)
	{
		led_flash_cnt = 6;
	}
	else
	{
		led_s = (enum LED_state)cmd;
	}
    return 0;
}

static struct device_ops led_ops =
{
    .ctrl = led_ctrl,
};

static void led_gpio_init(void)
{
    GPIO_InitStruType x;
    x.GPIO_Signal = GPIO_Pin_Signal_Digital;
    x.GPIO_Func = GPIO_Func_0;
    x.GPIO_Direction = GPIO_Dir_Out;
    x.GPIO_PUEN = GPIO_PUE_Input_Disable;
    x.GPIO_PDEN = GPIO_PDE_Input_Disable;
    x.GPIO_OD = GPIO_ODE_Output_Disable;
    x.GPIO_DS = GPIO_DS_Output_Normal;
    GPIO_Init(LED_PORT,LED_PIN,&x);
    LED_OFF;
}

static struct soft_timer led_tmr =
{
    .expires = INITIAL_JIFFIES + configHZ / 100,
    .cb      = led_tmr_cb,
};

int board_setup_led(void)
{
    led_gpio_init();
    led_dev.ops = &led_ops;
    device_register(&led_dev, "led", 0);
    soft_timer_add(&led_tmr);
    return 0;
}
device_initcall(board_setup_led);
